﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Practices.Unity.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder2;

namespace cludg.Infrastructure.DI.Unity.DependecyAttribute
{
	using Core.Attributes;

	internal class PropertySelectorPolicy : PropertySelectorBase<Dependency>
	{
		protected readonly IPropertySelectorPolicy PrevPolicy;

		public PropertySelectorPolicy(IPropertySelectorPolicy prevPolicy)
			: base()
		{
			PrevPolicy = prevPolicy;
		}

		public override IEnumerable<SelectedProperty> SelectProperties(IBuilderContext context, IPolicyList resolverPolicyDestination)
		{
			var result = base.SelectProperties(context, resolverPolicyDestination);

			if (PrevPolicy != null)
				result = result.Concat(PrevPolicy.SelectProperties(context, resolverPolicyDestination));

			return result;
		}

		protected override IDependencyResolverPolicy CreateResolver(PropertyInfo property)
		{
			var attributes =  property.GetCustomAttributes(typeof(Dependency), false);

			if (attributes.Length != 1)
				return null;

			return new NamedTypeDependencyResolverPolicy(property.PropertyType, ((Dependency)attributes[0]).ImplementationName);
		}
	}
}
